<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  medias
 */

class m_medias_actions_block_EditAction extends m_backoffice_extends_Action
{
	public function execute()
	{		
		$formValues = $this->getFormValues("form");

		$docId = $this->getRequestParameter("docId");
		$docLang = $this->getRequestParameter("docLang");
		
		if(is_null($docId)) $docId = $formValues["folderId"]; 
		if(is_null($docLang)) $docId = $formValues["folderLang"]; 
		
		$media = f_document_Provider::getInstance()->getByModelAndUniqueId('medias/Media', $this->getRequestParameter("mediaId"), $docLang);
		$folder = f_document_Provider::getInstance()->getByModelAndUniqueId('backoffice/Folder', $docId, $docLang);
		$mediaTag = m_backoffice_services_TagService::getInstance()->getTagByDocId($this->getRequestParameter("mediaId"), $docLang);

		$relationManager = f_relation_Manager::getInstance();
        //AJAX to link a media
        if(!is_null($this->getRequestParameter("linkedDocId")) && !is_null($this->getRequestParameter("linkAction")))
        {
            $linkedDocId = $this->getRequestParameter("linkedDocId");
            $action = $this->getRequestParameter("linkAction");

            $childDoc = $this->getDocumentProvider()->getByModelAndUniqueId("modules_medias/media", $linkedDocId, $docLang);

            if(is_object($childDoc))
            {
                if($action == "link")
                {
                    $relationManager->setRelation($media, $childDoc, "media", null, $docLang);
                }
                elseif($action == "unlink")
                {
                    $relationManager->clearRelation($media, $childDoc, "media", $docLang);
                }
            }
            return "1";
            exit();
        }

		if(count($formValues) > 0)
		{
            $newName = f_core_Routing::formatStringForUrl($formValues["title"]);
            $formValues['newName'] = $newName.".".$media->getExtension();
            
            $errors = $this->isValid($formValues, $folder);
            if(empty($errors))
            {
                $newName = f_core_Routing::formatStringForUrl($formValues["title"]);
                if($media->renameMedia($newName))
                {
                    $media	->setPublicationstatus($formValues["status"])
                            ->setAlt($formValues["alt"])
                            ->setTitle($formValues["title"])
                            ->setLabel($formValues['newName'])
                            ->setDescription($formValues["description"])
                            ->save();
                }

                if($formValues['submit'] == 'true') $this->addToModel('formSuccess', 'true');
            }
            else
            {
                $this->addToModel('errors', $errors);
            }
		}
        
		// Get values from ajax request by session for document navigation
		$rows = $this->getSession()->getValue("mediaRows");
		

        $this->addToModel("files", $media->getAllSizesImagesObjects());

        $this->addToModel("linkedMedia", $relationManager->getChilds($media, "media", $docLang));
        $this->addToModel("linkedMediaNb", $relationManager->getChildsNb($media, "media", $docLang));
		//$this->addToModel("navLinks", $this->getNavigationLinks($this->getRequestParameter("mediaId"), $rows, $docId, $docLang));
        $listService = m_backoffice_services_ListService::getInstance();
        $this->addToModel('nextImage', $listService->getNextDocument($media, array('read', 'edit')));
        $this->addToModel('previousImage', $listService->getPreviousDocument($media, array('read', 'edit')));
		$this->addToModel("rows", $rows);				
		$this->addToModel("media", $media);		
		$this->addToModel("folder", $folder);
		$this->addToModel("mediaTag", $mediaTag);
		$this->setView('success');
	}	
	
	public function validate()
	{
		return $this->getUserContext()->hasRight(array("backoffice_accessBo", "medias_Edit"));
	}

    private function isValid($formValues, $folder)
    {
        $errors = array();

        if(empty($formValues["title"]))
        {
            $errors['title'] = $this->getLocale('locale.medias.forms.required');
        }
        else
        {
            $nb = $this->getDocumentProvider()
                        ->loadDocuments("modules_medias/media")
                        ->isChildOf($folder->getUniqueId(), "media")
                        ->whereIsEqual("document_label", $formValues["newName"])
                        ->count($folder->getLang());

            if($nb > 0)
            {
                $errors['title'] = $this->getLocale('locale.medias.forms.exist');
            }
        }

        return $errors;
    }
	
	private function getNavigationLinks($currentId, $rows, $folderId, $lang)
	{
		foreach($rows as $key => $row)
		{
			if($row == $currentId)
			{
				$selected = $key;
			}
		}
		
		$links["nbRows"] = count($rows);
		$links["selected"] = $selected + 1;
		
		if(isset($rows[$selected - 1]))
		{
			$links["previous"] = f_core_Routing::getUrl("mediasEdit", array("docId" => $folderId, "mediaId" => $rows[$selected - 1], "docLang" => strtolower($lang)));
		}
		
		if(isset($rows[$selected + 1]))
		{
			$links["next"] = f_core_Routing::getUrl("mediasEdit", array("docId" => $folderId, "mediaId" => $rows[$selected + 1], "docLang" => strtolower($lang)));			
		}
		
		return $links;
	}
}